class ElementWrapper {
  constructor(type) {
    this.root = document.createElement(type);
  }
  
  setAttribute(key, value) {
    this.root.setAttribute(key, value);
  }
  
  appendChild(child) {
    this.root.appendChild(child.root);
  }
}

class TextWrapper {
  constructor(content) {
    this.root = document.createTextNode(content);
  }
}

class Component {
  constructor() {
    this.props = {};
    this.children = [];
    this._root = null;
  }
  
  setAttribute(key, value) {
    this.props[key] = value;
  }
  
  appendChild(child) {
    this.children.push(child);
  }
  
  get root() {
    if (!this._root) {
      // 自动形成一个递归调用
      this._root = this.render().root;
    }
    return this._root;
  }
}

function createElement(type, attributes, ...children) {
  let e;
  if (typeof type === "string") {
    e = new ElementWrapper(type);
  } else {
    e = new type;
  }
  
  for (let p in attributes) {
    e.setAttribute(p, attributes[p]);
  }
  
  const insertChildren = (children)=>{
    for (let child of children) {
      if (typeof child === "string") {
        child = new TextWrapper(child);
      }
      if (Array.isArray(child)){
        insertChildren(child)
      }else{
        e.appendChild(child);
      }
    }
  }
  insertChildren(children)
  return e;
}

const render = (component, parentElement) => {
  parentElement.appendChild(component.root);
};
export {
  createElement, Component, render,
};
